//
// Created by denglibin on 19-5-9.
//

#include "Camera.h"
/**
   * 构造函数
   */
Camera::Camera(){
}


/**
 * 前进
 * @param deltaTime
 */
void Camera::moveFront(float deltaTime){
    cameraPos += speedFactor * deltaTime * cameraFront; //前进
}
/**
 * 后退
 * @param deltaTime
 */
void Camera::moveBack(float deltaTime){
    cameraPos -= speedFactor * deltaTime * cameraFront; //后退
}
/**
 * 左移
 * @param deltaTime
 */
void Camera::moveLeft(float deltaTime){
    //cross向量叉乘 得到与两个向量都垂直第第三个向量
    //normalize:标准化坐标(转成-1到1)
    cameraPos -= glm::normalize(glm::cross(cameraFront, cameraUp)) * speedFactor * deltaTime; //左移动
}
/**
 * 右移
 * @param deltaTime
 */
void Camera::moveRight(float deltaTime){
    cameraPos += glm::normalize(glm::cross(cameraFront, cameraUp)) * speedFactor * deltaTime; //右移动
}
/**
 * 上移
 * @param deltaTime
 */
void Camera::moveUp(float deltaTime){
    cameraPos.y +=  speedFactor * deltaTime; //上移动
}
/**
 * 下移
 * @param deltaTime
 */
void Camera::moveDown(float deltaTime){
    cameraPos.y -=  speedFactor * deltaTime; //上移动
}


/**
 * 鼠标移动 改变摄像机方向 鼠标左移摄像机左转,鼠标右移摄像机右转,鼠标上移摄像机向上看,鼠标下移摄像机往下看
 * @param xPos 鼠标x坐标
 * @param yPos 鼠标y坐标
 */
void Camera::updateFront(double xPos, double yPos){
    if(firstMouse){
        lastX = xPos;
        lastY = yPos;
        firstMouse = false;
    }
    /**
     * 计算摄像机观察的方向 (鼠标左移摄像机左转,鼠标右移摄像机右转,鼠标上移摄像机向上看,鼠标下移摄像机往下看)
     */
    //计算当前帧和上一帧鼠标位置的偏移量
    float xoffset = xPos - lastX;
    float yoffset = lastY - yPos; // 反过来 屏幕坐标上面小,下面大
    lastX = xPos;
    lastY = yPos;

    xoffset *= sensitivity; //偏移量转成偏移角度
    yoffset *= sensitivity;

    pitch += yoffset; //最终角度
    yaw   -= xoffset;

    if(pitch > 89.0f)
        pitch =  89.0f;
    if(pitch < -89.0f)
        pitch = -89.0f;
    glm::vec3 front;
    front.x = cos(glm::radians(pitch)) * cos(glm::radians(yaw));//方向与向量的大小无关用单位向量即可,省略了 乘以1
    front.y = sin(glm::radians(pitch));
    front.z = -cos(glm::radians(pitch)) * sin(glm::radians(yaw)); //往屏幕里面看,取负

    cameraFront = glm::normalize(front); //新的方向
}
/**
 * 获取观察矩阵
 * @return
 */
glm::mat4 Camera::getViewMatrix(){
   // 摄像机位置+观察方向向量 = 目标位置
    return glm::lookAt(cameraPos, cameraPos + cameraFront, cameraUp); //参数:位置、目标(原点)和上向量
}